package com.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

/**
 * Date: 2024/6/18 22:06
 * Author: T_log
 * Description: NodeCacheDemo
 */
public class NodeCacheDemo {


    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);

        client.start();
        System.out.println("已经成功的连接ZK服务了....");

        NodeCache nodeCache = new NodeCache(client,"/cluster");

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                Stat stat = client.checkExists().forPath("/cluster");
                if (stat == null) {
                    System.out.println("stat is null , i am watch it");
                } else {
                    ChildData currentData = nodeCache.getCurrentData();
                    System.out.println(currentData.toString());
                }
            }
        });

        nodeCache.start();
    }
}
